package com.learn.springboot.web;

import com.learn.springboot.bean.User;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author dyz
 * @program learning
 * @create 2019-08-01 18:06
 */
@RestController
@RequestMapping("/users")
public class UserController {

    /**
     * 使用Map来模拟数据
     * 创建线程安全的Map
     */
    private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    /**
     * /users/的GET请求
     */
    @GetMapping("/")
    public List<User> getUserList() {
        return new ArrayList<>(users.values());
    }

    /**
     * /users/的POST请求
     */
    @PostMapping("/")
    public String postUser(@ModelAttribute User user) {
        // 除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(), user);
        return "success";
    }

    /**
     * /users/{id}的GET请求
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // url中的id可通过@PathVariable绑定到函数的参数中
        return users.get(id);
    }

    /**
     * /users/{id}的PUT请求
     */
    @PutMapping("/{id}")
    public String putUser(@PathVariable Long id, @ModelAttribute User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    /**
     * /users/{id}的DELETE请求
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}
